import { Button, InputNumber, Select, Space } from 'antd'
import { useEffect, useState } from 'react'

const { Option } = Select

const options = ['inherit', 'auto', 'px', '%', 'em', 'vh']

export function StyleSize(props: any) {
  const { value, onChange } = props
  const [unit, setUnit] = useState(options[0])
  const [val, setVal] = useState(value)

  useEffect(() => {
    let numberVal = ''
    let unit = ''
    if (value === 'auto' || value === 'inherit') {
      numberVal = ''
      unit = value
    }
    else if (String(value).includes('px')) {
      numberVal = String(value).replace('px', '')
      unit = 'px'
    }
    else if (String(value).includes('em')) {
      numberVal = String(value).replace('em', '')
      unit = 'em'
    }
    else if (String(value).includes('%')) {
      numberVal = String(value).replace('%', '')
      unit = '%'
    }
    else if (String(value).includes('em')) {
      numberVal = String(value).replace('em', '')
      unit = 'em'
    }
    else if (String(value).includes('vh')) {
      numberVal = String(value).replace('vh', '')
      unit = 'vh'
    }
    if (unit)
      setUnit(unit)

    setVal(numberVal)
  }, [value])

  return <Space >
        {(unit !== options[0] && unit !== options[1]) && <InputNumber value={val} defaultValue={0} onChange={(v) => {
          setVal(v)
          onChange && onChange(`${v}${unit}`)
        }} />}
        <Button style={{ width: 55 }} onClick={() => {
          const idx = options.indexOf(unit)
          let unitIdx = null
          if (idx === options.length - 1)
            unitIdx = 0
          else
            unitIdx = idx + 1

          setUnit(options[unitIdx])
          onChange && onChange((unitIdx === 0 || unitIdx === 1) ? options[unitIdx] : `${0}${options[unitIdx]}`)
        }} >{unit}</Button>
    </Space>
}
